/*
 ============================================================================
 Name        : starop.c
 Author      : chenf
 Version     :
 Copyright   : loongsec
 Description : Start or Stop LS_, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "cgi.h"
#include "cookie.h"
#include "stdx.h"

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
    printf("%s.\n", err_msg);
}

int main(void) {
    char  *zErrMsg = 0;
    char  *input;
    char  *req_method;
    int   rc = 1;
    int   type = 0;
    char  buf[120] = {0};
    char  buf_c[150] = {0};

    if(isvalid_cookie() != 0){
        return 0;
    }
    
    req_method = getenv("REQUEST_METHOD");  
    input = getcgidata((FILE*) stdin, req_method);

    PARAM act   = getParam(input, "op");
    PARAM preIP = getParam(input, "preip");
    PARAM repIP = getParam(input, "repip");

    if( strcmp(act.value, "ifconfig") == 0 ){
        //rc = system("service loongsec-cgi restart");
        sprintf(buf_c, "/home/www/cgi-bin/ipconf.sh %s %s", preIP.value, repIP.value);
        rc = system(buf_c);
        type = 9;
    } else if( strcmp(act.value, "restart") == 0 ){
        //rc = system("service loongsec-cgi restart");
        rc = system("/home/www/cgi-bin/lsmc.sh reboot");
        type = -1;
    } else if( strcmp(act.value, "start") == 0  ){
        //rc = system("service loongsec-cgi restart");
        rc = system("/home/www/cgi-bin/lsmc.sh restart");
        type = 1;
    } else if( strcmp(act.value, "stop") == 0){
        //rc = system("service loongsec-cgi stop");
        rc = system("/home/www/cgi-bin/lsmc.sh stop");
        type = 2;
    } else {
        //rc = system("service loongsec-cgi restart");
        type = 0;        
        FILE* stream = popen("/home/www/cgi-bin/lsmc.sh status", "r" );
        fread(buf, sizeof(char), sizeof(buf), stream);
        pclose( stream ); 
    }
    printf("Content-type:text/json;charset=UTF-8\n\n");
    printf("{\"action\":\"%s\", \"type\":\"%d\", \"res\":\"%d\", \"status\":\"%s\"}\n", act.value, type, rc, buf);
    
    return 0;

}

